package com.sykj.cloud.system.service.impl;

import com.sykj.cloud.common.core.constant.UserConstants;
import com.sykj.cloud.common.core.utils.DateUtils;
import com.sykj.cloud.common.core.utils.IdUtils;
import com.sykj.cloud.common.core.utils.StringUtils;
import com.sykj.cloud.common.security.utils.SecurityUtils;
import com.sykj.cloud.system.api.domain.SysRole;
import com.sykj.cloud.system.api.domain.SysUser;
import com.sykj.cloud.system.domain.SysUserRole;
import com.sykj.cloud.system.mapper.SysRoleMapper;
import com.sykj.cloud.system.mapper.SysUserMapper;
import com.sykj.cloud.system.mapper.SysUserRoleMapper;
import com.sykj.cloud.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 系统用户Service业务层处理
 *
 * @author mr.will
 * @date 2021-03-23
 */
@Service
public class SysUserServiceImpl implements ISysUserService
{
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    SysRoleMapper sysRolesMapper;
    @Autowired
    SysUserRoleMapper sysUserRoleMapper;

    /**
     * 新增系统用户
     *
     * @param sysUser 系统用户
     * @return 结果
     */
    @Override
    public int insertSysUser(SysUser sysUser)
    {
        // 新增用户
        sysUser.setGuid(IdUtils.fastSimpleUUID());
        sysUser.setCreateTime(DateUtils.getNowDate());

        sysUser.setCreateBy("");
        // 密码加密
        sysUser.setLoginPassword(SecurityUtils.encryptPassword(sysUser.getLoginPassword()));
        int rows = sysUserMapper.insertSysUser(sysUser);
        // 新增用户关联数据
        insertUserRole(sysUser);
        return rows;
    }



    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user)
    {
        String[] roles = user.getRoleIds();
        if (StringUtils.isNotNull(roles))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (String roleId : roles)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getGuid());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0)
            {
                sysUserRoleMapper.batchUserRole(list);
            }
        }
    }

    /**
     * 修改系统用户
     *
     * @param sysUser 系统用户
     * @return 结果
     */
    @Override
    public int updateSysUser(SysUser sysUser)
    {

        String userId = sysUser.getGuid();
        // 删除用户与角色关联
        sysUserRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(sysUser);
//        // 删除用户与岗位关联
//        userPostMapper.deleteUserPostByUserId(userId);
//        // 新增用户与岗位管理
//        insertUserPost(user);
        sysUser.setUpdateTime(DateUtils.getNowDate());
        return sysUserMapper.updateSysUser(sysUser);
    }

    @Override
    public int updateSysUserVaildStatus(SysUser user) {
        return sysUserMapper.updateSysUser(user);
    }

    @Override
    public int updateUserProfile(SysUser user) {
        return sysUserMapper.updateSysUser(user);
    }

    @Override
    public boolean updateUserAvatar(String loginName, String avatar) {
        return sysUserMapper.updateUserAvatar(loginName, avatar) > 0;
    }

    @Override
    public int resetPwd(SysUser user) {
        return sysUserMapper.updateSysUser(user);
    }

    @Override
    public int resetUserPwd(String loginName, String password) {
        return sysUserMapper.resetUserPwd(loginName, password);
    }

    /**
     * 批量删除系统用户
     *
     * @param guids 需要删除的系统用户ID
     * @return 结果
     */
    @Override
    public int deleteSysUserByIds(String[] guids)
    {
        return sysUserMapper.deleteSysUserByIds(guids);
    }

    /**
     * 删除系统用户信息
     *
     * @param guid 系统用户ID
     * @return 结果
     */
    @Override
    public int deleteSysUserById(String guid)
    {
        return sysUserMapper.deleteSysUserById(guid);
    }

    /**
     * 查询系统用户
     *
     * @param guid 系统用户ID
     * @return 系统用户
     */
    @Override
    public SysUser getSysUserById(String guid)
    {
        return sysUserMapper.getSysUserById(guid);
    }

    /**
     * 查询系统用户列表
     *
     * @param sysUser 系统用户
     * @return 系统用户
     */
    @Override
    public List<SysUser> listSysUsers(SysUser sysUser)
    {
        return sysUserMapper.listSysUsers(sysUser);
    }

    @Override
    public SysUser getUserByLoginName(String loginName) {
        return sysUserMapper.getUserByLoginName(loginName);
    }


    @Override
    public String getUserRoleGroup(String loginName) {
        List<SysRole> list = sysRolesMapper.getRoleByLoginName(loginName);
        StringBuffer idsStr = new StringBuffer();
        for (SysRole role : list)
        {
            idsStr.append(role.getName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString()))
        {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    @Override
    public String getUserPostGroup(String loginName) {

//        List<SysPost> list = postMapper.selectPostsByUserName(userName);
//        StringBuffer idsStr = new StringBuffer();
//        for (SysPost post : list)
//        {
//            idsStr.append(post.getPostName()).append(",");
//        }
//        if (StringUtils.isNotEmpty(idsStr.toString()))
//        {
//            return idsStr.substring(0, idsStr.length() - 1);
//        }
//        return idsStr.toString();

       return null;
    }

    @Override
    public String checkLoginNameUnique(String loginName) {
        int count = sysUserMapper.checkLoginNameUnique(loginName);
        if (count > 0)
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public String checkPhoneUnique(SysUser user) {
        String userId = StringUtils.isNull(user.getGuid()) ? "" : user.getGuid();
        SysUser info = sysUserMapper.checkPhoneUnique(user.getPhone());
        if (StringUtils.isNotNull(info) && !info.getGuid().equals(user.getGuid()))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public String checkEmailUnique(SysUser user) {
        String userId = StringUtils.isNull(user.getGuid()) ? "" : user.getGuid();
        SysUser info = sysUserMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && !info.getGuid().equals(user.getGuid()))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public void checkUserAllowed(SysUser user) {
//        if (StringUtils.isNotNull(user.getGuid()) && user.isAdmin())
//        {
//            throw new CustomException("不允许操作超级管理员用户");
//        }
    }

    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
//        if (StringUtils.isNull(userList) || userList.size() == 0)
//        {
//            throw new CustomException("导入用户数据不能为空！");
//        }
//        int successNum = 0;
//        int failureNum = 0;
//        StringBuilder successMsg = new StringBuilder();
//        StringBuilder failureMsg = new StringBuilder();
//        String password = configService.selectConfigByKey("sys.user.initPassword");
//        for (SysUser user : userList)
//        {
//            try
//            {
//                // 验证是否存在这个用户
//                SysUser u = userMapper.selectUserByUserName(user.getUserName());
//                if (StringUtils.isNull(u))
//                {
//                    user.setPassword(SecurityUtils.encryptPassword(password));
//                    user.setCreateBy(operName);
//                    this.insertUser(user);
//                    successNum++;
//                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
//                }
//                else if (isUpdateSupport)
//                {
//                    user.setUpdateBy(operName);
//                    this.updateUser(user);
//                    successNum++;
//                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
//                }
//                else
//                {
//                    failureNum++;
//                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
//                }
//            }
//            catch (Exception e)
//            {
//                failureNum++;
//                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
//                failureMsg.append(msg + e.getMessage());
//                log.error(msg, e);
//            }
//        }
//        if (failureNum > 0)
//        {
//            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
//            throw new CustomException(failureMsg.toString());
//        }
//        else
//        {
//            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
//        }
//        return successMsg.toString();
        return null;
    }


}
